import {AxiosError, AxiosInstance, AxiosResponse, InternalAxiosRequestConfig} from "axios";
import {message} from 'antd'
import {STORAGE} from "@/const";

export function interceptor(axios: AxiosInstance) {
    axios.interceptors.request.use(
        (config: InternalAxiosRequestConfig) => {
            try {
                const v = localStorage.getItem(STORAGE.AUTH_KEY)
                const {token} = v ? JSON.parse(v) : {}
                config.headers.set('Authorization', `Bearer ${token}`);
            } catch (err) {
                console.error(err)
            }
            return config;
        },
        (error: AxiosError) => {
            return Promise.reject(error);
        })
    axios.interceptors.response.use(
        (response: AxiosResponse) => {
            const {data} = response
            const {code, message: msg} = data
            if (code === 200) {
                return response;
            } else {
                message.error(msg)
                return Promise.reject(msg)
            }
        },
        async (error: AxiosError) => {
            message.error(error.message)
            return Promise.reject(error.message);
        })
}